package zticker

import (
	"time"
)

type Ticker struct {
	ticker   *time.Ticker
	stopChan chan int8
}

type Timer struct {
	timer    *time.Timer
	stopChan chan int8
}

type Handle func()

// Check 间隔执行(秒)
func (c *Ticker) Check(intervalSec int, f Handle) {
	go func() {
		c.ticker = time.NewTicker(time.Duration(intervalSec) * time.Second)
		for {
			select {
			case <-c.ticker.C:
				f()
			case <-c.stopChan:
				c.ticker.Stop()
				return
			}
		}
	}()
}

func (c *Ticker) Stop() {
	//c.ticker.Stop()
	close(c.stopChan)
}

func (c *Ticker) Restart(sec int) {
	c.ticker.Reset(time.Duration(sec) * time.Second)
}

// Timing 定时执行
func (c *Timer) Timing(hour, min, sec int, f Handle) {
	c.stopChan = make(chan int8, 1)
	go func() {
		for {
			now := time.Now()
			targetTime := time.Date(now.Year(), now.Month(), now.Day(), hour, min, sec, 0, now.Location())

			if now.After(targetTime) {
				targetTime = targetTime.Add(24 * time.Hour)
			}
			c.timer = time.NewTimer(targetTime.Sub(now))
			select {
			case <-c.timer.C:
				f()
			}
		}
	}()
}

// OnHour 整点执行
func (c *Timer) OnHour(f Handle) {
	// 计算到下一个整点的时间差
	now := time.Now().UTC()
	nextHour := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, now.Location()).Add(time.Hour)
	duration := nextHour.Sub(now)

	// 创建定时器
	c.timer = time.NewTimer(duration)
	for {
		select {
		case <-c.timer.C:
			f()
			// 重置定时器
			c.timer.Reset(time.Hour)
		case <-c.stopChan:
			c.timer.Stop()
			return
		}
	}
}

func (c *Timer) Stop() {
	//c.ticker.Stop()
	close(c.stopChan)
}
